package com.runchamp;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.internal.app.WindowDecorActionBar;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

public class ChooseRace extends ActionBarActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    public String path = "http://runtobo.appspot.com/racesManager";
    Spinner distanceSpinner, dateSpinner;
    RadioButton distanceRadioButton, dateRadioButton;
    private Intent intent;
    private Intent raceIntent;
    private Intent intentCreate;
    private JSONAdapterRacesList mJSONAdapter;
    private long user;
    private Button timeButton, distanceButton, racersButton;
    private FloatingActionButton floatingActionButton;
    private int highlight;
    private int barText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_race);

        //get user from shared prefs
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        user = Long.valueOf(prefs.getString("userID", ""));

        //Init layout
        highlight = getResources().getColor(R.color.highlight);
        barText = getResources().getColor(R.color.action_bar_text);
        timeButton = (Button) findViewById(R.id.button_time);
        distanceButton = (Button) findViewById(R.id.button_distance);
        racersButton = (Button) findViewById(R.id.button_racers);
        racersButton.setTextColor(highlight);
        floatingActionButton = (FloatingActionButton) findViewById(R.id.normal_plus);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createRace(v);
            }
        });

        //Init intents
        intent = new Intent(this, RaceInfo.class);
        intentCreate = new Intent(this, CreateRace.class);

        //Init list view
        ListView racesListView;
        mJSONAdapter = new JSONAdapterRacesList(this, getLayoutInflater(), true);
        racesListView = (ListView) findViewById(R.id.main_listview);
        racesListView.setAdapter(mJSONAdapter);
        racesListView.setOnItemClickListener(this);
        racesListView.setOnItemLongClickListener(this);

        //action bar
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        WindowDecorActionBar bar = (WindowDecorActionBar) actionBar;
        bar.setDisplayHomeAsUpEnabled(true);
        bar.setHomeButtonEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.show();
        bar.show();

        //build client and get request for getting all races
        AsyncHttpClient client = new AsyncHttpClient();

        client.get(String.format("%s/futureRaces?user=%s", path, user),
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(JSONArray jsonObject) {
                        mJSONAdapter.updateData(jsonObject);
                        mJSONAdapter.sortByDistance();
                    }

                    @Override
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
                    }
                });

    }


    //////Activity Functions///////

    protected void onRestart() {
        super.onRestart();
    }

    protected void onStart() {
        super.onStart();
    }

    protected void onResume() {

        super.onResume();

        //get user from shared prefs
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        user = Long.valueOf(prefs.getString("userID", ""));

        //Init layout
        distanceButton.setTextColor(barText);
        timeButton.setTextColor(barText);
        racersButton.setTextColor(highlight);

        //Init intents
        intent = new Intent(this, RaceInfo.class);
        intentCreate = new Intent(this, CreateRace.class);

        //Init list view
        ListView racesListView;
        mJSONAdapter = new JSONAdapterRacesList(this, getLayoutInflater(), true);
        racesListView = (ListView) findViewById(R.id.main_listview);
        racesListView.setAdapter(mJSONAdapter);
        racesListView.setOnItemClickListener(this);
        racesListView.setOnItemLongClickListener(this);

        //build client and get request for getting all races
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(String.format("%s/futureRaces?user=%s", path, user),
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(JSONArray jsonObject) {
                        mJSONAdapter.updateData(jsonObject);
                        mJSONAdapter.sortByDistance();
                    }

                    @Override
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
                    }
                });

    }

    @Override
    public void onBackPressed() {
        finish();
        this.overridePendingTransition(R.anim.nothing, R.anim.slide_out_right);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.overridePendingTransition(R.anim.nothing, R.anim.slide_out_right);
    }


    //////Option Menue///////

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_choose_race, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        switch (item.getItemId()) {
            case 16908332:
                finish();
                this.overridePendingTransition(R.anim.nothing, R.anim.slide_out_right);
                return true;
            case R.id.action_filter:
                filterRaces(null);
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }


    //////Select race from list///////

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //get selected race
        JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);
        //collect data
        Bundle raceBundle = new Bundle();
        raceBundle.putString("Key", jsonObject.optString("Key"));
        raceBundle.putString("Tags", jsonObject.optString("Tags"));
        raceBundle.putString("Distance", jsonObject.optString("Distance"));
        raceBundle.putString("Time", jsonObject.optString("Time"));
        raceBundle.putString("Manager", jsonObject.optString("Manager"));
        raceBundle.putString("ManagerId", jsonObject.optString("ManagerId"));
        raceBundle.putString("Participants", jsonObject.optString("Participants"));
        raceBundle.putString("Estimated", jsonObject.optString("Estimated"));
        raceBundle.putString("Privacy", jsonObject.optString("Privacy"));
        //go to race info and push data
        intent.putExtras(raceBundle);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        //get selected race
        JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);
        //build client and post request
        final AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user", String.valueOf(user));
        params.put("race", jsonObject.optString("Key"));

        //add user to race
        client.post(String.format("%s/addUserToRace", path), params, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(JSONArray jsonObject) {
                //get update races list
                client.get(String.format("%s/futureRaces?user=%s", path, user),
                        new JsonHttpResponseHandler() {

                            @Override
                            public void onSuccess(JSONArray jsonObject) {
                                mJSONAdapter.updateData(jsonObject);
                                mJSONAdapter.sortByDistance();
                            }

                            @Override
                            public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                                Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
                            }
                        });
                Toast.makeText(getApplicationContext(), "Joined successfully!", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
            }
        });


        return true;
    }

    //////Create race ///////

    public void createRace(View view) {
        startActivity(intentCreate);
    }


    //////Sort functions///////

    public void sortByDistance(View view) {
        distanceButton.setTextColor(highlight);
        timeButton.setTextColor(barText);
        racersButton.setTextColor(barText);
        mJSONAdapter.sortByDistance();
    }

    public void sortByTime(View view) {
        distanceButton.setTextColor(barText);
        timeButton.setTextColor(highlight);
        racersButton.setTextColor(barText);
        mJSONAdapter.sortByTime();
    }

    public void sortByParticipants(View view) {
        distanceButton.setTextColor(barText);
        timeButton.setTextColor(barText);
        racersButton.setTextColor(highlight);
        mJSONAdapter.sortByParticipants();
    }

    //////filter dialog box//////

    public void filterRaces(View view) {

        LayoutInflater inflater = getLayoutInflater();
        View promptView = inflater.inflate(R.layout.dialog_races_filter, null);
        final AlertDialog dialogFilter = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AppDialog))
                .setView(promptView)
                .setPositiveButton(R.string.OK, null)
                .setCancelable(true)
                .setTitle("Filter Races")
                .create();

        dialogFilter.show();

        //init the layout
        distanceSpinner = (Spinner) promptView.findViewById(R.id.spinner_distance);
        dateSpinner = (Spinner) promptView.findViewById(R.id.spinner_date);
        final RadioGroup radioGroup = (RadioGroup) promptView.findViewById(R.id.radioFilter);
        distanceRadioButton = (RadioButton) promptView.findViewById(R.id.radioButton_distance);
        dateRadioButton = (RadioButton) promptView.findViewById(R.id.radioButton_date);
        distanceSpinner.setEnabled(true);
        dateSpinner.setEnabled(false);

        //submit the dialog and update the jsonArray
        Button buttonOK = dialogFilter.getButton(AlertDialog.BUTTON_POSITIVE);
        buttonOK.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String getString;

                //set the get request according to the checked radio button
                switch (radioGroup.getCheckedRadioButtonId()) {
                    case R.id.radioButton_distance:
                        int requiredDistance = (int) distanceSpinner.getSelectedItemPosition();
                        getString = String.format("%s/futureRacesFilterByDistance?user=%s&distance=%s", path, user, requiredDistance);
                        break;
                    case R.id.radioButton_date:
                        int requiredDate = (int) dateSpinner.getSelectedItemPosition();
                        getString = String.format("%s/futureRacesFilterByDate?user=%s&date=%s", path, user, requiredDate);
                        break;
                    default:
                        getString = String.format("%s/futureRaces?user=%s", path, user);
                }


                AsyncHttpClient client = new AsyncHttpClient();
                //get update races list
                client.get(getString,
                        new JsonHttpResponseHandler() {

                            @Override
                            public void onSuccess(JSONArray jsonObject) {
                                mJSONAdapter.updateData(jsonObject);
                                mJSONAdapter.sortByDistance();
                                dialogFilter.dismiss();
                            }

                            @Override
                            public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                                Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
                            }
                        });
            }
        });

    }

    public void radioButtonOnClick(View view) {
        distanceSpinner.setEnabled(distanceRadioButton.isChecked());
        dateSpinner.setEnabled(dateRadioButton.isChecked());
    }


}
